import { showToast, navigateTo } from "utils/index";
import { GetSearchSongsSugList, GetSearchSongsHotList } from "apis/index";
Page({
  data: {
    searchVal: "",
    sugList: [],
    isFold: true,
    historyList: [],
    hotSearchList: [],
  },

  onLoad(options) {
    this.getHistoryList();
    this.getHotSearchList();
  },
  onShow() {
    this.setData({
      searchVal: "",
      sugList: [],
    });
  },
  onShareAppMessage() {},
  onInput(e) {
    const value = e.detail;
    if (!value) {
      this.setData({
        sugList: [],
      });
      return;
    }
    GetSearchSongsSugList({ keywords: value, limit: 10 }).then((res) => {
      let list = res.songs || [];
      list = list.map((it) => {
        const html = it.name.replace(
          new RegExp(value, "g"),
          `<span style="color:red;">${value}</span>`
        );
        return {
          html,
          text: it.name,
        };
      });
      this.setData({
        sugList: list,
      });
    });
  },
  //确认搜索
  onSearch(e) {
    const value = e.detail;
    this.addHistoryList(value, true);
    this.setData({
      currPage: 1,
    });
    this.toSearchResultPage(value);
  },
  //清除搜索内容
  onClearSearchVal() {
    this.setData({
      sugList: [],
    });
  },
  //获取热门搜索列表
  getHotSearchList() {
    GetSearchSongsHotList().then((res) => {
      this.setData({
        hotSearchList: res || [],
      });
    });
  },
  //切换历史记录的折叠按钮状态
  toggleExpandStatus() {
    const { isExpand } = this.data;
    this.setData({
      isExpand: !isExpand,
    });
  },
  //获取历史记录
  getHistoryList() {
    let list = [];
    wx.getStorage({
      key: "searchHistoryList",
      success: (res) => {
        list = res.data || [];
        this.setData({
          historyList: list,
        });
      },
      fail: (err) => {
        this.setData({
          historyList: [],
        });
      },
    });
  },
  //清除历史记录
  clearHistoryList() {
    wx.showModal({
      title: "温馨提示",
      content: "是否清除全部搜索记录？",
      confirmText: "清除",
      success: (res) => {
        if (res.confirm) {
          wx.setStorageSync("searchHistoryList", []);
          this.setData({
            historyList: [],
          });
          showToast("清除成功");
        } else if (res.cancel) {
          console.log("用户点击取消");
        }
      },
    });
  },
  /**
   * 将搜索词添加进历史记录
   * @param val {string} 要添加的搜索记录值
   * @param isFreshList {boolean} 添加完后，是否要立即刷新历史记录列表
   */
  addHistoryList(val, isFreshList = false) {
    val = val.trim();
    if (!val) return;
    let list = wx.getStorageSync("searchHistoryList") || [];
    list.unshift(val);
    list = Array.from(new Set(list));
    if (list.length > 20) {
      list = list.slice(0, 20);
    }
    wx.setStorageSync("searchHistoryList", list);
    if (isFreshList) {
      this.getHistoryList();
      this.toSearchResultPage(val);
    }
  },
  //前往搜索结果页
  toSearchResultPage(val) {
    navigateTo(`/pages/result/result?value=${val}`);
  },
  //点击历史记录时
  onHistoryListItem(e) {
    const { val } = e.currentTarget.dataset;
    this.setData({
      searchVal: val,
    });
    this.toSearchResultPage(val);
  },
  //切换历史记录折叠状态
  toggleFold() {
    this.setData({
      isFold: !this.data.isFold,
    });
  },
  //点击联想下拉项时
  onSugItem(e) {
    const { html, text } = e.detail;
    this.toSearchResultPage(text);
  },
});
